# -*- coding: utf-8 -*-
from __future__ import unicode_literals

class PairBase(object):
    '''
    成对规则部分的解析基类

    params:
        key_char: 关键字符
        cache_key: 缓存键
        escape_char: 转义字符

    return:
        {
            'content': <str> 解析处理后的字符串
            'cache': <dict> 解析替换的字符串键值对缓存
        }
    '''
    def __init__(self, content, key_char, cache_key, key_len=1, escape_char='\\'):
        super(PairBase, self).__init__()
        self.content = content
        self.key_char = key_char
        self.cache_key = cache_key
        self.key_len = key_len
        self.escape_char = escape_char

    @property
    def states(self):
        # return {}
        raise NotImplementedError()

    def _getStateKey(self, state):
        '''根据状态值获取状态键'''
        for _k in self.states:
            if state == self.states[_k]:
                return _k

    def _toHtml(self, content):
        '''转化为html'''
        return content

    def _wrapperResult(self, cache):
        '''包装解析结果'''
        ret = {
            'content': self.content,
            'cache': {}
        }
        if bool(cache):
            _tmp = []
            _cache = {}
            _begin = 0
            for _k in cache:
                _v = cache[_k]
                _cache[_k] = self._toHtml(_v['content'][self.key_len:-self.key_len])
                _c = self.content[_begin : _v['start']]
                _tmp.append(_c)
                _tmp.append(_k)
                _begin = _v['end']
            if _begin < len(self.content):
                _c = self.content[_begin:]
                _tmp.append(_c)
            ret['content'] = ''.join(_tmp)
            ret['cache'] = _cache
        return ret

    def parse(self):
        '''执行解析操作'''
        # return self._wrapperResult({})
        raise NotImplementedError()